package com.miyake.loveviewweb.client.account;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.miyake.loveviewweb.client.service.DataService;
import com.miyake.loveviewweb.client.service.DataServiceAsync;

public class GoogleLogin extends Composite {

	List<LoginListener> listeners = new ArrayList<LoginListener>();
	public void addLoginListener(LoginListener handler) {
	    listeners.add(handler);
	}
	protected void fireLogin(boolean login) {
		for (LoginListener handler : listeners) {
			handler.onLogin(login);
		}
	}
	  
	protected void fireRequestLogin(String url) {
        for (LoginListener handler : listeners) {
            handler.onRequestLogin(url);
        }
    }

	   
	private LoginInfo loginInfo = null;
	private HorizontalPanel loginPanel = new HorizontalPanel();
	private HorizontalPanel mainPanel = new HorizontalPanel();
	private Anchor signInLink = new Anchor("Sign in");
	private Anchor signOutLink = new Anchor("Sign out");
 
	protected void loadLogin() {
	    signInLink.setHref(loginInfo.getLoginUrl());
	    loginPanel.add(signInLink);
	    verticalPanel.add(loginPanel);
	}
  
	protected void loadMain() {
		mainPanel.add(new HTML("<b>"+ loginInfo.getEmail()+"</b>"));
		mainPanel.add(new Label(" | "));
		mainPanel.add(signOutLink);
		signOutLink.setHref(loginInfo.getLogoutUrl());
		verticalPanel.add(mainPanel);
  }

	HorizontalPanel verticalPanel;
	public GoogleLogin(LoginListener listener, String url) {
	    this.addLoginListener(listener);
		verticalPanel = new HorizontalPanel();
		initWidget(verticalPanel);
		DataServiceAsync loginService = DataService.Util.getInstance();
		    loginService.login(url ,
    		new AsyncCallback<LoginInfo>(){
    			public void onFailure(Throwable error){
    			    Window.alert(error.getMessage());
    			}
        
    			public void onSuccess(LoginInfo result){
    				loginInfo = result;
    				if(loginInfo.isLoggedInLoveView()){
    					loadMain();
    					fireLogin(true);
    				}
    				else {   				   
    				    fireRequestLogin(result.getLoginUrl());
    				}
    			}
    		});
	
	
	}

}
